#!/usr/bin/env node

import inquirer from 'inquirer';
import chalk from 'chalk';
import ora from 'ora';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { ConfigManager } from './config/configManager.js';
import SFTPClient from './sftp/sftpClient.js';
import { Logger } from './utils/logger.js';
import { validateConfigExists, validateLocalFileExists, validateLocalDirExists } from './utils/configHelper.js';
import { withSftpConnection } from './utils/sftpHelper.js';
import { normalizeLocalPath, normalizeRemotePath, joinRemotePath } from './utils/pathUtils.js';
import SshConfigManager from './config/sshConfigManager.js';

// 获取版本号
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const packagePath = path.join(__dirname, '..', 'package.json');
const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
const VERSION = packageJson.version;

const configManager = new ConfigManager();
const sftpClient = new SFTPClient();
const sshConfigManager = new SshConfigManager();

// 处理命令行参数
const args = process.argv.slice(2);

async function main() {
  try {
    // 处理快速命令
    if (args.length > 0) {
      await handleQuickCommand();
      return;
    }

    Logger.banner();
    
    const { action } = await inquirer.prompt([
      {
        type: 'list',
        name: 'action',
        message: '选择操作',
        choices: [
          { name: '🚀 快速连接', value: 'quick' },
          { name: '⚙️  管理配置', value: 'config' },
          { name: '❌ 退出', value: 'exit' }
        ]
      }
    ]);

    switch (action) {
      case 'quick':
        await quickConnect();
        break;
      case 'config':
        await manageConfig();
        break;
      case 'exit':
        Logger.info('再见！');
        process.exit(0);
    }
  } catch (error) {
    Logger.error(`错误: ${error.message}`);
    process.exit(1);
  }
}

async function handleQuickCommand() {
  try {
    const command = args[0];

    // 显示版本信息
    if (['-v', '--version'].includes(command)) {
      console.log(`SFTPX CLI v${VERSION}`);
      process.exit(0);
    }

    // 显示使用帮助
    if (['-h', '--help', 'help'].includes(command)) {
      showHelp();
      process.exit(0);
    }

    // 快速增加配置: sftpx set-auth name:配置名 账号 密码
    if (command === 'set-auth') {
      if (args.length < 4) {
        Logger.error('用法: sftpx set-auth name:配置名 账号 密码');
        Logger.error('示例: sftpx set-auth name:myserver user123 pass123');
        process.exit(1);
      }
      const nameArg = args[1];
      const username = args[2];
      const password = args[3];
      const host = args[4] || 'localhost';
      const port = parseInt(args[5]) || 22;
      
      const nameMatch = nameArg.match(/name:(.+)/);
      if (!nameMatch) {
        Logger.error('配置名格式错误，应为: name:myserver');
        process.exit(1);
      }
      const configName = nameMatch[1];
      await setAuth(configName, host, port, username, password);
      return;
    }

    // 查看配置: sftpx get-auth 配置名
    if (command === 'get-auth') {
      if (args.length < 2) {
        Logger.error('用法: sftpx get-auth 配置名');
        process.exit(1);
      }
      const configName = args[1];
      await getAuth(configName);
      return;
    }

    // 检查远程目录: sftpx --check [配置名] 远程路径
    if (command === '--check' || command === '-c' || command === 'check') {
      if (args.length < 3) {
        Logger.error('用法: sftpx --check [配置名] 远程路径');
        Logger.error('示例: sftpx --check cloud-note /home/taixd');
        process.exit(1);
      }
      const configName = args[1];
      const remotePath = normalizeRemotePath(args[2]);
      await checkRemoteDir(configName, remotePath);
      return;
    }

    // 快速连接: sftpx -ssh 配置名
    if (command === '-ssh' || command === '--ssh') {
      if (args.length < 2) {
        Logger.error('用法: sftpx -ssh 配置名');
        Logger.error('示例: sftpx -ssh myserver');
        process.exit(1);
      }
      const configName = args[1];
      await quickConnectWithConfig(configName);
      return;
    }

    // 导出SSH配置: sftpx --export-ssh 配置名 [别名]
    if (command === '--export-ssh') {
      if (args.length < 2) {
        Logger.error('用法: sftpx --export-ssh 配置名 [别名]');
        Logger.error('示例: sftpx --export-ssh myserver');
        Logger.error('示例: sftpx --export-ssh myserver myalias');
        process.exit(1);
      }
      const configName = args[1];
      const alias = args[2]; // 可选参数
      await exportSshConfig(configName, alias);
      return;
    }

    // 导出所有SSH配置: sftpx --export-all-ssh
    if (command === '--export-all-ssh') {
      await exportAllSshConfigs();
      return;
    }

    // 列出SSH配置: sftpx --list-ssh
    if (command === '--list-ssh') {
      await listSshConfigs();
      return;
    }

    // 移除SSH配置: sftpx --remove-ssh 别名
    if (command === '--remove-ssh') {
      if (args.length < 2) {
        Logger.error('用法: sftpx --remove-ssh 别名');
        Logger.error('示例: sftpx --remove-ssh myalias');
        process.exit(1);
      }
      const alias = args[1];
      await removeSshConfig(alias);
      return;
    }

    // 删除配置: sftpx remove-auth 配置名 或 sftpx -r auth:配置名
    if (command === 'remove-auth' || command === '-r') {
      let configName;
      if (command === 'remove-auth') {
        if (args.length < 2) {
          Logger.error('用法: sftpx remove-auth 配置名');
          process.exit(1);
        }
        configName = args[1];
      } else {
        if (args.length < 2) {
          Logger.error('用法: sftpx -r auth:配置名');
          process.exit(1);
        }
        const authArg = args[1];
        const authMatch = authArg.match(/auth:(.+)/);
        if (!authMatch) {
          Logger.error('配置名格式错误，应为: auth:myserver');
          process.exit(1);
        }
        configName = authMatch[1];
      }
      await removeAuth(configName);
      return;
    }

    // 上传命令: sftpx --put [配置名] 本地文件 远程目录
    if (command === '--put' || command === '-p' || command === 'put') {
      if (args.length < 3) {
        Logger.error('用法: sftpx --put [配置名] 本地文件 远程目录');
        Logger.error('示例: sftpx --put myserver ./file.txt /home/user/');
        process.exit(1);
      }
      const configName = args[1];
      const localFile = normalizeLocalPath(args[2]);
      let remoteDir = args[3] ? normalizeRemotePath(args[3]) : '/';
      
      await quickUpload(configName, localFile, remoteDir);
      return;
    }

    // 下载命令: sftpx --get [配置名] 远程文件 [本地目录]
    if (command === '--get' || command === '-g' || command === 'get') {
      if (args.length < 3) {
        Logger.error('用法: sftpx --get [配置名] 远程文件 [本地目录]');
        Logger.error('示例: sftpx --get myserver /home/user/file.txt ./');
      }
      const configName = args[1];
      const remoteFile = normalizeRemotePath(args[2]);
      let localDir = args[3] ? normalizeLocalPath(args[3]) : process.cwd();
      
      await quickDownload(configName, remoteFile, localDir);
      await quickDownload(configName, remoteFile, localDir);
      await batchUpload(configName, patterns, remoteDir);
      return;
    }

    // 批量下载命令: sftpx --mget [配置名] 远程文件模式 本地目录
    if (command === '--mget' || command === '-mg' || command === 'mget') {
      if (args.length < 3) {
        Logger.error('用法: sftpx --mget [配置名] 远程文件模式 本地目录');
        Logger.error('示例: sftpx --mget myserver "/home/user/*.txt" ./downloads');
        process.exit(1);
      }
      const configName = args[1];
      const patterns = args[2];
      let localDir = args[3] ? normalizeLocalPath(args[3]) : process.cwd();
      
      await batchDownload(configName, patterns, localDir);
      return;
    }

    Logger.error(`未知命令: ${command}`);
    showHelp();
    process.exit(1);
  } catch (error) {
    Logger.error(`错误: ${error.message}`);
    process.exit(1);
  }
}

function showHelp() {
  // 获取终端宽度
  const width = process.stdout.columns || 80;
  const contentWidth = Math.min(width - 4, 76); // 留出边框空间
  
  // 创建分隔线函数
  const createLine = (char) => char.repeat(contentWidth);
  
  // 创建居中文本函数
  const centerText = (text) => {
    const padding = Math.max(0, Math.floor((contentWidth - text.length) / 2));
    return ' '.repeat(padding) + text;
  };
  
  // 创建带边框的文本行
  const createBorderedLine = (text) => {
    // 确保文本长度不超过内容宽度
    const truncatedText = text.length > contentWidth ? text.substring(0, contentWidth) : text;
    return truncatedText.padEnd(contentWidth);
  };
  
  // 构建帮助内容
  const helpContent = [
    chalk.cyan(createLine('─')),
    chalk.cyan(createBorderedLine(centerText('SFTPX CLI 快速命令用法'))),
    chalk.cyan(createLine('─')),
    '',
    chalk.yellow('[配置管理]'),
    '',
    `  ${chalk.green('set-auth')}      快速增加配置`,
    `    用法: sftpx set-auth name:myserver 账号 密码 [主机] [端口]`,
    `    示例: sftpx set-auth name:myserver user123 pass123 192.168.1.1 22`,
    '',
    `  ${chalk.green('get-auth')}      读取配置信息`,
    `    用法: sftpx get-auth 配置名`,
    `    示例: sftpx get-auth myserver`,
    '',
    `  ${chalk.green('remove-auth')}   删除配置 (方式1)`,
    `    用法: sftpx remove-auth 配置名`,
    `    示例: sftpx remove-auth myserver`,
    '',
    `  ${chalk.green('-r')}            删除配置 (方式2)`,
    `    用法: sftpx -r auth:配置名`,
    `    示例: sftpx -r auth:myserver`,
    '',
    chalk.yellow('[文件传输]'),
    '',
    `  ${chalk.green('--check, -c')}  检查远程目录`,
    `    用法: sftpx --check 配置名 远程路径`,
    `    示例: sftpx --check myserver /home/user`,
    '',
    `  ${chalk.green('--put, -p')}     上传文件到远程目录`,
    `    用法: sftpx --put 配置名 本地文件 远程目录`,
    `    示例: sftpx --put myserver ./file.txt /home/user/`,
    '',
    `  ${chalk.green('--get, -g')}     从远程下载文件到本地`,
    `    用法: sftpx --get 配置名 远程文件 [本地目录]`,
    `    示例: sftpx --get myserver /home/user/file.txt ./`,
    `    (本地目录默认为当前目录)`,
    '',
    `  ${chalk.green('--mput, -mp')}   批量上传文件到远程目录`,
    `    用法: sftpx --mput 配置名 文件模式 远程目录`,
    `    示例: sftpx --mput myserver "*.txt" /home/user/`,
    `    示例: sftpx --mput myserver "./src/**/*.{js,ts}" /home/user/project/`,
    '',
    `  ${chalk.green('--mget, -mg')}   批量下载远程文件到本地`,
    `    用法: sftpx --mget 配置名 远程文件模式 本地目录`,
    `    示例: sftpx --mget myserver "/home/user/*.txt" ./downloads`,
    `    示例: sftpx --mget myserver "/home/user/**/*.{jpg,png}" ./images`,
    `  ${chalk.green('--get, -g')}     从远程下载文件到本地`,
    `    用法: sftpx --get 配置名 远程文件 [本地目录]`,
    '',
    `    (本地目录默认为当前目录)`,
    `    示例: sftpx --ssh myserver`,
    `    (连接后进入交互式文件传输菜单)`,
    '',
    `  ${chalk.green('--export-ssh')}  导出SSH配置`,
    `    用法: sftpx --export-ssh 配置名 [别名]`,
    `    示例: sftpx --export-ssh myserver`,
    `    示例: sftpx --export-ssh myserver myalias`,
    `    ${chalk.red('注意: 在Windows上需要已安装SSH客户端(如Git Bash或OpenSSH)')}`,
    '',
    `  ${chalk.green('--export-all-ssh')}  导出所有SSH配置`,
    `    用法: sftpx --export-all-ssh`,
    `    ${chalk.red('注意: 在Windows上需要已安装SSH客户端(如Git Bash或OpenSSH)')}`,
    '',
    `  ${chalk.green('--list-ssh')}  列出导出的SSH配置`,
    `    用法: sftpx --list-ssh`,
    '',
    `  ${chalk.green('--remove-ssh')}  移除SSH配置`,
    `    用法: sftpx --remove-ssh 别名`,
    `    示例: sftpx --remove-ssh myalias`,
    '',
    `  ${chalk.green('-v, --version')} 查看版本信息`,
    `  ${chalk.green('-h, --help')}   查看帮助信息`,
    `  ${chalk.green('(无参数)')}     进入交互菜单`,
    '',
    chalk.cyan(`─${createLine('─')}─`)
  ];
  
  // 输出帮助内容
  console.log(helpContent.join('\n'));
}

async function quickUpload(configName, localFile, remoteDir) {
  try {
    const configs = configManager.listConfigs();
    const config = configs[configName];

    if (!config) {
      Logger.error(`配置不存在: ${configName}`);
      Logger.info(`可用配置: ${Object.keys(configs).join(', ') || '无'}`);
      process.exit(1);
    }

    // 验证本地文件
    if (!fs.existsSync(localFile)) {
      Logger.error(`本地文件不存在: ${localFile}`);
      process.exit(1);
    }

    const spinner = ora('连接中...').start();
    await sftpClient.connect(config);
    spinner.succeed('连接成功');

    const fileName = path.basename(localFile);
    const remoteFilePath = remoteDir.endsWith('/') 
      ? remoteDir + fileName 
      : remoteDir + '/' + fileName;

    const uploadSpinner = ora(`上传中: ${fileName}...`).start();
    await sftpClient.uploadFile(localFile, remoteFilePath);
    uploadSpinner.succeed(`上传成功: ${remoteFilePath}`);
    
    await sftpClient.disconnect();
    process.exit(0);
  } catch (error) {
    Logger.error(`上传失败: ${error.message}`);
    await sftpClient.disconnect().catch(() => {});
    process.exit(1);
  }
}

async function quickDownload(configName, remoteFile, localDir) {
  try {
    const configs = configManager.listConfigs();
    const config = configs[configName];

    if (!config) {
      Logger.error(`配置不存在: ${configName}`);
      Logger.info(`可用配置: ${Object.keys(configs).join(', ') || '无'}`);
      process.exit(1);
    }

    // 确保本地目录存在，如果不存在则尝试创建
    if (!fs.existsSync(localDir)) {
      try {
        fs.mkdirSync(localDir, { recursive: true });
      } catch (error) {
        Logger.error(`无法创建目录: ${localDir}`);
        Logger.error(`错误: ${error.message}`);
        process.exit(1);
      }
    }

    const spinner = ora('连接中...').start();
    await sftpClient.connect(config);
    spinner.succeed('连接成功');

    const fileName = path.basename(remoteFile);
    const localFilePath = path.join(localDir, fileName);

    const downloadSpinner = ora(`下载中: ${fileName}...`).start();
    await sftpClient.downloadFile(remoteFile, localFilePath);
    downloadSpinner.succeed(`下载成功: ${localFilePath}`);
    
    await sftpClient.disconnect();
    process.exit(0);
  } catch (error) {
    Logger.error(`下载失败: ${error.message}`);
    await sftpClient.disconnect().catch(() => {});
    process.exit(1);
  }
}

// 快速增加配置
async function setAuth(configName, host, port, username, password) {
  try {
    const config = {
      host,
      port,
      username,
      password,
      authType: 'password',
    };
    
    configManager.saveConfig(configName, config);
    Logger.success(`配置已保存: ${configName}`);
    console.log(`主机: ${host}:${port}`);
    console.log(`账号: ${username}`);
    process.exit(0);
  } catch (error) {
    Logger.error(`保存配置失败: ${error.message}`);
    process.exit(1);
  }
}

// 读取配置
async function getAuth(configName) {
  try {
    const configs = configManager.listConfigs();
    const config = configs[configName];

    if (!config) {
      Logger.error(`配置不存在: ${configName}`);
      Logger.info(`可用配置: ${Object.keys(configs).join(', ') || '无'}`);
      process.exit(1);
    }

    console.log('');
    console.log(chalk.cyan(`配置: ${configName}`));
    console.log(`主机: ${config.host}`);
    console.log(`端口: ${config.port}`);
    console.log(`账号: ${config.username}`);
    console.log(`认证方式: ${config.authType === 'password' ? '密码' : '秘钒'}`);
    if (config.authType === 'password') {
      console.log(`密码: ${config.password}`);
    } else {
      console.log(`秘钒路径: ${config.privateKeyPath}`);
    }
    console.log('');
    process.exit(0);
  } catch (error) {
    Logger.error(`读取配置失败: ${error.message}`);
    process.exit(1);
  }
}

// 删除配置
async function removeAuth(configName) {
  try {
    const configs = configManager.listConfigs();
    const config = configs[configName];

    if (!config) {
      Logger.error(`配置不存在: ${configName}`);
      Logger.info(`可用配置: ${Object.keys(configs).join(', ') || '无'}`);
      process.exit(1);
    }

    configManager.deleteConfig(configName);
    Logger.success(`配置已删除: ${configName}`);
    process.exit(0);
  } catch (error) {
    Logger.error(`删除配置失败: ${error.message}`);
    process.exit(1);
  }
}

// 检查远程目录
async function checkRemoteDir(configName, remotePath) {
  try {
    const configs = configManager.listConfigs();
    const config = configs[configName];

    if (!config) {
      Logger.error(`配置不存在: ${configName}`);
      process.exit(1);
    }

    const spinner = ora('连接中...').start();
    await sftpClient.connect(config);
    spinner.succeed('连接成功');

    console.log('');
    console.log(`检查远程路径: ${remotePath}`);
    
    try {
      const files = await sftpClient.listFiles(remotePath);
      console.log(chalk.green('✓ 目录存在！'));
      console.log('');
      console.log(`目录内容 (${files.length} 个项目):`);
      
      if (files.length === 0) {
        console.log('  (目录为空)');
      } else {
        files.forEach(file => {
          const type = file.longname.startsWith('d') ? '📁' : '📄';
          const size = file.longname.startsWith('d') ? '' : ` (${(file.attrs.size / 1024).toFixed(2)} KB)`;
          const perms = file.longname.substring(0, 10);
          console.log(`  ${type} ${file.filename}${size} [${perms}]`);
        });
      }
      console.log('');
      console.log(chalk.green('✓ 目录可以读取'));
    } catch (error) {
      if (error.message.includes('No such file')) {
        console.log(chalk.red('✗ 目录不存在'));
        console.log(`   需要执行: mkdir ${remotePath}`);
      } else if (error.message.includes('Permission denied')) {
        console.log(chalk.red('✗ 没有访问权限'));
        console.log('   需要更高的权限或使用其他目录');
      } else {
        console.log(chalk.red(`✗ 错误: ${error.message}`));
      }
      console.log('');
    }

    await sftpClient.disconnect();
    process.exit(0);
  } catch (error) {
    Logger.error(`检查失败: ${error.message}`);
    await sftpClient.disconnect().catch(() => {});
    process.exit(1);
  }
}

// 快速连接到指定配置的服务器
async function quickConnectWithConfig(configName) {
  try {
    const configs = configManager.listConfigs();
    const config = configs[configName];

    if (!config) {
      Logger.error(`配置不存在: ${configName}`);
      Logger.info(`可用配置: ${Object.keys(configs).join(', ') || '无'}`);
      process.exit(1);
    }

    const spinner = ora('连接中...').start();
    await sftpClient.connect(config);
    spinner.succeed('连接成功');

    Logger.info(`已连接到 ${config.host}:${config.port}`);
    Logger.info('现在可以使用交互式菜单进行文件操作');

    // 导入文件传输菜单
    const { fileTransferMenu } = await import('./menus/fileTransferMenu.js');
    
    // 进入文件传输菜单
    await fileTransferMenu(sftpClient, configManager, config);
    
    await sftpClient.disconnect();
    process.exit(0);
  } catch (error) {
    Logger.error(`连接失败: ${error.message}`);
    await sftpClient.disconnect().catch(() => {});
    process.exit(1);
  }
}

async function quickConnect() {
  const configs = configManager.listConfigs();
  const configNames = Object.keys(configs);

  if (configNames.length === 0) {
    Logger.warn('没有保存的配置');
    const { createNew } = await inquirer.prompt([
      {
        type: 'confirm',
        name: 'createNew',
        message: '要创建新配置吗？',
        default: true
      }
    ]);
    
    if (!createNew) {
      return;
    }
    
    await createConfig();
    return;
  }

  const { selectedConfig } = await inquirer.prompt([
    {
      type: 'list',
      name: 'selectedConfig',
      message: '选择要连接的服务器',
      choices: [
        ...configNames.map(name => ({ name, value: name })),
        new inquirer.Separator(),
        { name: '➕ 创建新配置', value: 'new' }
      ]
    }
  ]);

  if (selectedConfig === 'new') {
    await createConfig();
    return;
  }

  const config = configs[selectedConfig];
  await connectAndTransfer(config);
}

async function createConfig() {
  const { host, port, username, authType } = await inquirer.prompt([
    {
      type: 'input',
      name: 'host',
      message: '服务器地址',
      validate: input => input ? true : '服务器地址不能为空'
    },
    {
      type: 'number',
      name: 'port',
      message: 'SSH 端口',
      default: 22
    },
    {
      type: 'input',
      name: 'username',
      message: '用户名',
      validate: input => input ? true : '用户名不能为空'
    },
    {
      type: 'list',
      name: 'authType',
      message: '认证方式',
      choices: [
        { name: '密码', value: 'password' },
        { name: '私钥', value: 'key' }
      ]
    }
  ]);

  let password, privateKeyPath, passphrase;

  if (authType === 'password') {
    const { pwd } = await inquirer.prompt([
      {
        type: 'password',
        name: 'pwd',
        message: '密码',
        validate: input => input ? true : '密码不能为空'
      }
    ]);
    password = pwd;
  } else {
    const { keyPath, hasPassphrase } = await inquirer.prompt([
      {
        type: 'input',
        name: 'keyPath',
        message: '私钥路径',
        validate: input => input ? true : '路径不能为空'
      },
      {
        type: 'confirm',
        name: 'hasPassphrase',
        message: '私钥需要密码短语吗？',
        default: false
      }
    ]);
    
    privateKeyPath = keyPath;
    
    if (hasPassphrase) {
      const { phrase } = await inquirer.prompt([
        {
          type: 'password',
          name: 'phrase',
          message: '密码短语'
        }
      ]);
      passphrase = phrase;
    }
  }

  const { saveName } = await inquirer.prompt([
    {
      type: 'input',
      name: 'saveName',
      message: '保存配置名称',
      validate: input => {
        if (!input) return '名称不能为空';
        if (configManager.listConfigs()[input]) return '配置已存在';
        return true;
      }
    }
  ]);

  const newConfig = {
    host,
    port,
    username,
    authType,
    password,
    privateKeyPath,
    passphrase
  };

  configManager.saveConfig(saveName, newConfig);
  await connectAndTransfer(newConfig);
}

async function connectAndTransfer(config) {
  const spinner = ora('连接中...').start();
  
  try {
    await sftpClient.connect(config);
    spinner.succeed('连接成功');

    let continueTransfer = true;
    while (continueTransfer) {
      const { operation } = await inquirer.prompt([
        {
          type: 'list',
          name: 'operation',
          message: '选择操作',
          choices: [
            { name: '📤 上传文件', value: 'upload' },
            { name: '📥 下载文件', value: 'download' },
            { name: '📂 浏览目录', value: 'list' },
            new inquirer.Separator(),
            { name: '❌ 断开连接', value: 'exit' }
          ]
        }
      ]);

      switch (operation) {
        case 'upload':
          await handleUpload();
          break;
        case 'download':
          await handleDownload();
          break;
        case 'list':
          await handleList();
          break;
        case 'exit':
          continueTransfer = false;
          break;
      }
    }
  } catch (error) {
    spinner.fail('连接失败');
    Logger.error(error.message);
  } finally {
    await sftpClient.disconnect();
  }
}

async function handleUpload() {
  const { localFile, remotePath } = await inquirer.prompt([
    {
      type: 'input',
      name: 'localFile',
      message: '本地文件路径',
      validate: input => input ? true : '路径不能为空'
    },
    {
      type: 'input',
      name: 'remotePath',
      message: '远程文件路径',
      validate: input => input ? true : '路径不能为空'
    }
  ]);

  const spinner = ora('上传中...').start();
  try {
    await sftpClient.uploadFile(localFile, remotePath);
    spinner.succeed('上传成功');
  } catch (error) {
    spinner.fail('上传失败');
    Logger.error(error.message);
  }
}

async function batchUpload(configName, patterns, remoteDir) {
  try {
    const configs = configManager.listConfigs();
    const config = configs[configName];

    if (!config) {
      Logger.error(`配置不存在: ${configName}`);
      Logger.info(`可用配置: ${Object.keys(configs).join(', ') || '无'}`);
      process.exit(1);
    }

    const spinner = ora('连接中...').start();
    await sftpClient.connect(config);
    spinner.succeed('连接成功');

    Logger.info(`开始批量上传: ${patterns} -> ${remoteDir}`);
    
    const uploadSpinner = ora('批量上传中...').start();
    const result = await sftpClient.uploadFiles(patterns, remoteDir, {
      maxConcurrent: 3,
      preserveStructure: true,
      verifyIntegrity: false,
      resume: true,
      onProgress: (progress) => {
        const percent = Math.round((progress.completed / progress.total) * 100);
        uploadSpinner.text = `批量上传中... ${progress.completed}/${progress.total} (${percent}%)`;
      }
    });
    
    if (result.success) {
      uploadSpinner.succeed(`批量上传完成: ${result.uploaded.length} 成功, ${result.failed.length} 失败, ${result.skipped.length} 跳过`);
    } else {
      uploadSpinner.fail('批量上传失败');
      Logger.error(result.error);
    }
    
    await sftpClient.disconnect();
    process.exit(0);
  } catch (error) {
    Logger.error(`批量上传失败: ${error.message}`);
    await sftpClient.disconnect().catch(() => {});
    process.exit(1);
  }
}

async function batchDownload(configName, patterns, localDir) {
  try {
    const configs = configManager.listConfigs();
    const config = configs[configName];

    if (!config) {
      Logger.error(`配置不存在: ${configName}`);
      Logger.info(`可用配置: ${Object.keys(configs).join(', ') || '无'}`);
      process.exit(1);
    }

    // 确保本地目录存在
    if (!fs.existsSync(localDir)) {
      try {
        fs.mkdirSync(localDir, { recursive: true });
        Logger.info(`已创建目录: ${localDir}`);
      } catch (error) {
        Logger.error(`无法创建目录: ${localDir}`);
        Logger.error(`错误: ${error.message}`);
        process.exit(1);
      }
    }

    const spinner = ora('连接中...').start();
    await sftpClient.connect(config);
    spinner.succeed('连接成功');

    Logger.info(`开始批量下载: ${patterns} -> ${localDir}`);
    
    const downloadSpinner = ora('批量下载中...').start();
    const result = await sftpClient.downloadFiles(patterns, localDir, {
      maxConcurrent: 3,
      preserveStructure: true,
      verifyIntegrity: false,
      resume: true,
      onProgress: (progress) => {
        const percent = Math.round((progress.completed / progress.total) * 100);
        downloadSpinner.text = `批量下载中... ${progress.completed}/${progress.total} (${percent}%)`;
      }
    });
    
    if (result.success) {
      downloadSpinner.succeed(`批量下载完成: ${result.downloaded.length} 成功, ${result.failed.length} 失败, ${result.skipped.length} 跳过`);
    } else {
      downloadSpinner.fail('批量下载失败');
      Logger.error(result.error);
    }
    
    await sftpClient.disconnect();
    process.exit(0);
  } catch (error) {
    Logger.error(`批量下载失败: ${error.message}`);
    await sftpClient.disconnect().catch(() => {});
    process.exit(1);
  }
}

async function handleDownload() {
  const { remotePath, localPath } = await inquirer.prompt([
    {
      type: 'input',
      name: 'remotePath',
      message: '远程文件路径',
      validate: input => input ? true : '路径不能为空'
    },
    {
      type: 'input',
      name: 'localPath',
      message: '本地保存路径',
      validate: input => input ? true : '路径不能为空'
    }
  ]);

  const spinner = ora('下载中...').start();
  try {
    await sftpClient.downloadFile(remotePath, localPath);
    spinner.succeed('下载成功');
  } catch (error) {
    spinner.fail('下载失败');
    Logger.error(error.message);
  }
}

async function handleList() {
  const { path } = await inquirer.prompt([
    {
      type: 'input',
      name: 'path',
      message: '目录路径（默认 /）',
      default: '/'
    }
  ]);

  const spinner = ora('加载中...').start();
  try {
    const files = await sftpClient.listFiles(path);
    spinner.succeed('加载完成');
    
    if (files.length === 0) {
      Logger.warn('目录为空');
      return;
    }

    const fileChoices = files.map(file => ({
      name: `${file.longname.startsWith('d') ? '📁' : '📄'} ${file.filename}`,
      value: file.filename
    }));

    console.log('');
    files.forEach(file => {
      const type = file.longname.startsWith('d') ? '📁' : '📄';
      const size = file.longname.startsWith('d') ? '' : ` (${formatBytes(file.attrs.size)})`;
      console.log(`${type} ${file.filename}${size}`);
    });
    console.log('');
  } catch (error) {
    spinner.fail('加载失败');
    Logger.error(error.message);
  }
}

async function manageConfig() {
  const configs = configManager.listConfigs();
  const configNames = Object.keys(configs);

  if (configNames.length === 0) {
    Logger.warn('没有保存的配置');
    return;
  }

  const { action } = await inquirer.prompt([
    {
      type: 'list',
      name: 'action',
      message: '配置管理',
      choices: [
        { name: '📋 查看所有配置', value: 'list' },
        { name: '🗑️  删除配置', value: 'delete' }
      ]
    }
  ]);

  if (action === 'list') {
    console.log('');
    configNames.forEach(name => {
      const config = configs[name];
      console.log(chalk.cyan(`${name}:`));
      console.log(`  主机: ${config.host}:${config.port}`);
      console.log(`  用户: ${config.username}`);
      console.log(`  认证: ${config.authType === 'password' ? '密码' : '私钥'}`);
    });
    console.log('');
  } else {
    const { toDelete } = await inquirer.prompt([
      {
        type: 'list',
        name: 'toDelete',
        message: '选择要删除的配置',
        choices: configNames
      }
    ]);

    const { confirm } = await inquirer.prompt([
      {
        type: 'confirm',
        name: 'confirm',
        message: `确定删除 "${toDelete}" 吗？`,
        default: false
      }
    ]);

    if (confirm) {
      configManager.deleteConfig(toDelete);
      Logger.success(`已删除 "${toDelete}"`);
    }
  }
}

function formatBytes(bytes) {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
}

// SSH配置管理相关函数
async function exportSshConfig(configName, alias) {
  try {
    const spinner = ora('导出SSH配置中...').start();
    
    // 检查配置是否存在
    const configs = configManager.listConfigs();
    const config = configs[configName];
    
    if (!config) {
      spinner.fail('配置不存在');
      Logger.error(`配置 "${configName}" 不存在`);
      Logger.info(`可用配置: ${Object.keys(configs).join(', ') || '无'}`);
      process.exit(1);
    }
    
    // 为配置添加name属性，以便在exportConfigAsync中使用
    config.name = configName;
    
    // 使用SSH配置管理器导出配置
    const result = await sshConfigManager.exportConfigAsync(config, alias);
    
    if (result.success) {
      spinner.succeed('SSH配置导出成功');
      Logger.info(`配置已导出到: ${result.configPath}`);
      Logger.info(`SSH别名: ${result.alias}`);
      Logger.info(`使用方法: ssh ${result.alias}`);
    } else {
      spinner.fail('SSH配置导出失败');
      Logger.error(result.error);
      process.exit(1);
    }
  } catch (error) {
    Logger.error(`导出SSH配置失败: ${error.message}`);
    process.exit(1);
  }
}

async function exportAllSshConfigs() {
  try {
    const spinner = ora('导出所有SSH配置中...').start();
    
    // 获取所有配置
    const configs = configManager.listConfigs();
    const configNames = Object.keys(configs);
    
    if (configNames.length === 0) {
      spinner.fail('没有可导出的配置');
      Logger.warn('没有保存的配置');
      process.exit(1);
    }
    
    // 使用SSH配置管理器导出所有配置
    const results = await sshConfigManager.exportAllConfigsAsync(configs);
    
    spinner.succeed('SSH配置导出完成');
    
    if (results.successCount > 0) {
      Logger.success(`成功导出 ${results.successCount} 个配置`);
      results.successful.forEach(result => {
        Logger.info(`  - ${result.configName} -> ${result.alias}`);
      });
    }
    
    if (results.failureCount > 0) {
      Logger.error(`${results.failureCount} 个配置导出失败`);
      results.failed.forEach(result => {
        Logger.error(`  - ${result.configName}: ${result.error}`);
      });
    }
    
    Logger.info(`配置已导出到: ${results.configPath}`);
  } catch (error) {
    Logger.error(`导出所有SSH配置失败: ${error.message}`);
    process.exit(1);
  }
}

async function listSshConfigs() {
  try {
    const spinner = ora('获取SSH配置列表...').start();
    
    // 使用SSH配置管理器获取配置列表
    const result = await sshConfigManager.listExportedConfigsAsync();
    
    spinner.succeed('SSH配置列表获取完成');
    
    if (result.configs.length === 0) {
      Logger.warn('没有导出的SSH配置');
      return;
    }
    
    console.log('');
    console.log(chalk.cyan('导出的SSH配置:'));
    console.log('');
    
    result.configs.forEach(config => {
      const marker = config.isSftpxExport ? chalk.green('[SFTPX]') : chalk.gray('[外部]');
      console.log(`${marker} ${chalk.yellow(config.alias)}: ${config.host}:${config.port} (${config.user})`);
      if (config.isSftpxExport) {
        console.log(`  源配置: ${config.sourceConfig}`);
      }
    });
    
    console.log('');
    console.log(`配置文件: ${result.configPath}`);
  } catch (error) {
    Logger.error(`获取SSH配置列表失败: ${error.message}`);
    process.exit(1);
  }
}

async function removeSshConfig(alias) {
  try {
    const spinner = ora('移除SSH配置中...').start();
    
    // 使用SSH配置管理器移除配置
    const result = await sshConfigManager.removeConfigAsync(alias);
    
    if (result.success) {
      spinner.succeed('SSH配置移除成功');
      Logger.info(`已移除配置: ${alias}`);
    } else {
      spinner.fail('SSH配置移除失败');
      Logger.error(result.error);
      process.exit(1);
    }
  } catch (error) {
    Logger.error(`移除SSH配置失败: ${error.message}`);
    process.exit(1);
  }
}

main();


